import json
import time
import hashlib
import requests
from GeTuiPublicManager import GeTui


# 获取SHA256加密字符串
def get_sha256(s):
    sha256 = hashlib.sha256()
    sha256.update(s.encode('utf-8'))
    return sha256.hexdigest()


# 获取鉴权token
def get_token_request():
    # 获取时间戳
    timestamp = int(time.time() * 1000)
    sign = get_sha256(GeTui.appkey + str(timestamp) + GeTui.mastersecret)
    url = GeTui.baseUrl + '/auth'
    headers = {
        'Content-Type': 'application/json;charset=UTF-8',
        "Accept": "application/json;charset=utf-8"
    }
    data = {
        'sign': sign,
        'appkey': GeTui.appkey,
        'timestamp': timestamp
    }

    response = requests.post(url, headers=headers, data=json.dumps(data))
    response_dict = response.json()
    GeTui.token = response_dict["data"]["token"]
    token = response_dict["data"]["token"]
    print("获取token成功")
    print("token ===" + token)
    print(type(response_dict))
    print(response_dict)
    # print(response_dict["msg"])
    # print(response_dict.keys[0])


# 删除token
def delete_token(token):
    if len(token) == 0:
        print("token不能为空")
        return
    url = url = GeTui.baseUrl + '/auth/' + token
    print('url == ' + url)
    headers = {
        'Content-Type': 'application/json;charset=UTF-8',
        "Accept": "application/json;charset=utf-8"
    }
    response = requests.delete(url=url, headers=headers)
    print("删除token请求")
    print(response.json())


# 获取token请求
get_token_request()
# 删除token
delete_token(GeTui.token)
